#!/bin/sh
clear

#++++++++++++++++++++1.设置环境变量++++++++++++++++++++++++++
#whereis 'infreemeeting'
#sudo apt purge 'infreemeeting'

read -p "请输入待扫描的IP段(如192.168.1):" IPDuan
read -p "请输入远端的用户名:" remoteUser
read -p "请输入远端的登录密码:" remotePwd
read -p "请输入当前系统密码(本地):" LocalPwd
RunDir=$(cd $(dirname $0);pwd)  #获取运行目录
remoteDir=/home/uos/Desktop # 设置远端桌面目录,请使用绝对路径..........................................
echo "正在扫描开放了22号端口的IP段($IPDuan.1-255), 请稍后................."
iplist=$(nmap -p 22 $IPDuan.1-255 | grep -oP "([0-9]{1,3}\.){3}[0-9]{1,3}")  #1.获取网络中开启了22号端口的IP地址和密码的集合
LocalIP=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}')	#获取本机IP地址,便于后面删除列表中的自己
#=======================自动应答函数======================================
func_expect()
{
    for line in $iplist
    do
        echo $line && echo $RunDir/$localFiles
        expect -c "
            spawn ssh $remoteUser@$line $cmd
            expect {
                \"(yes/no)\" {send \"yes\r\"; exp_continue}
                \"password:\" {send \"$remotePwd"\r\"; exp_continue}
            }"
    done
}
#=============================================================
# sed -i /^"${LocalIP}"/d ./ip.txt	#删除列表中的本机IP地址,避免SSh时,操作到本机
# ListFiles=ip.txt
# cat $iplist
localFiles=infreeMeeting.uos.amd64.2.0.1.deb

# remoteIP=192.168.1.117  #   远端ip

#++++++++++++++++++++2.设置要运行的命令++++++++++++++++++++++++++
cmd="scp -r ${RunDir}/${localFiles} ${remoteUser}@${line}:${remoteDir}"	#待运行的命令
#cmd="echo '123qwe' | sudo -S apt install ${remoteDir}/${localFiles} -y"	#待运行的命令


if ! type nmap >/dev/null 2>&1;then echo $LocalPwd | sudo -S apt install nmap -y;fi
if ! type expect >/dev/null 2>&1;then echo $LocalPwd | sudo -S apt install expect -y;fi
#--------------------------------------------------------------


 func_expect $CMD

    # if [ c == 1; ]; then
    #     CMD=scp -r ${RunDir}/${localFiles} ${remoteUser}@${ip}:${remoteDir}
    # elif [ c = 2; ]; then
    #     CMD==ssh -t ${remoteUser}@${i} echo ${remotePwd} | sudo -S apt install $remoteDir/$localFiles -y
    # else
    #     # else body
    # fi